package gui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.GridLayout;
import java.awt.Image;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import network.GetOrderWorker;
import data.DepartmentData;
import data.GetOrderListResponse;
import data.Order;
import data.Order.OrderState;
import data.OrderResponse;
import data.ProductInfo;
import data.SaveResponse;

public class MainPanel extends JPanel {
	private static final long serialVersionUID = -3168605646704333609L;

	private AppletMenuBarDemo mParent = null;
	private JLabel mClientLogo;
	private JLabel mClientDataLabel;
	private JLabel mAdmelLogo;
	private JLabel mVendorDataLabel;
	private OrderTabbedPane mTabbedPane = null;

	public static final float MAX_LOGO_HEIGHT = 80.0f;
	public static final float MAX_LOGO_WIDTH = 280.0f;

	private static Map<Integer, ProductInfo> mProducts = null;
	private static Map<Integer, DepartmentData> mDepartments = null;

	private Map<Integer, ProductInfo> generateProductHashMap(List<ProductInfo> products) {
		HashMap<Integer, ProductInfo> map = new HashMap<>();
		for (ProductInfo product : products)
			map.put(product.getDbId(), product);
		return map;
	}

	private Map<Integer, DepartmentData> generateDepartmentHashMap(List<DepartmentData> departments) {
		HashMap<Integer, DepartmentData> map = new HashMap<>();
		for (DepartmentData department : departments)
			map.put(department.getId(), department);
		return map;
	}

	public static ProductInfo getProductByDbId(int dbId) {
		return mProducts.get(dbId);
	}

	public static DepartmentData getDepartmentByDbId(int dbId) {
		return mDepartments.get(dbId);
	}

	/**
	 * Create the panel.
	 */
	public MainPanel(AppletMenuBarDemo parent) {
		mParent = parent;

		setLayout(new BorderLayout(0, 0));
		setSize(800, 394);

		JPanel panel = new JPanel();
		add(panel, BorderLayout.NORTH);
		panel.setLayout(new GridLayout(0, 2, 0, 0));

		JPanel clientPanel = new JPanel();
		clientPanel.setBorder(new TitledBorder(null, "Klient", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel.add(clientPanel);
		Border paddingBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
		clientPanel.setLayout(new BorderLayout(0, 0));

		mClientLogo = new JLabel("");
		clientPanel.add(mClientLogo, BorderLayout.NORTH);
		// clientLogo.setIcon(new
		// ImageIcon("D:\\KOPIA\\tata\\client_logo.png"));
		mClientLogo.setHorizontalAlignment(SwingConstants.CENTER);

		mClientDataLabel = new JLabel("Dane klienta");
		mClientDataLabel.setHorizontalAlignment(SwingConstants.LEFT);
		mClientDataLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
		clientPanel.add(mClientDataLabel, BorderLayout.SOUTH);
		mClientDataLabel.setBorder(paddingBorder);

		JPanel vendorPanel = new JPanel();
		vendorPanel.setBorder(new TitledBorder(null, "Sprzedawca", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel.add(vendorPanel);
		vendorPanel.setLayout(new BorderLayout(0, 0));

		mAdmelLogo = new JLabel("");
		mAdmelLogo.setHorizontalAlignment(SwingConstants.CENTER);
		// admelLogo.setIcon(new ImageIcon("D:\\KOPIA\\tata\\admel_logo.png"));
		vendorPanel.add(mAdmelLogo);

		mVendorDataLabel = new JLabel("Dane sprzedawcy");
		vendorPanel.add(mVendorDataLabel, BorderLayout.SOUTH);
		mVendorDataLabel.setBorder(paddingBorder);

		JPanel panel_1 = new JPanel();
		add(panel_1, BorderLayout.CENTER);
		panel_1.setLayout(new BorderLayout(0, 0));

		mTabbedPane = new OrderTabbedPane(JTabbedPane.TOP);
		mTabbedPane.addChangeListener(new ChangeListener() {

			@Override
			public void stateChanged(ChangeEvent arg0) {
				mClientDataLabel.setVisible(mTabbedPane.getSelectedIndex() == 0);
				mVendorDataLabel.setVisible(mTabbedPane.getSelectedIndex() == 0);
			}
		});
		panel_1.add(mTabbedPane);
	}

	public void setImages(String image1, String address1, String image2, String address2) {
		Image icon = null;
		Image icon2 = null;
		try {
			icon = new ImageIcon(new URL(image1)).getImage();
			icon2 = new ImageIcon(new URL(image2)).getImage();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		float width = icon.getWidth(null) / (icon.getHeight(null) / MAX_LOGO_HEIGHT);
		float height = MAX_LOGO_HEIGHT;
		if (width > MAX_LOGO_WIDTH) {
			width = MAX_LOGO_WIDTH;
			height = icon.getHeight(null) / (icon.getWidth(null) / MAX_LOGO_WIDTH);
		}
		mClientLogo.setIcon(new ImageIcon(icon.getScaledInstance((int) width, (int) height, Image.SCALE_SMOOTH)));

		width = icon2.getWidth(null) / (icon2.getHeight(null) / height);
		mAdmelLogo.setIcon(new ImageIcon(icon2.getScaledInstance((int) width, (int) height, Image.SCALE_SMOOTH)));

		mClientDataLabel.setText(address1);
		mVendorDataLabel.setText(address2);
	}

	public void setObjects(List<DepartmentData> objects) {
		mDepartments = generateDepartmentHashMap(objects);
		mTabbedPane.setObjects(mDepartments.values());
	}

	public void setProducts(List<ProductInfo> products) {
		mProducts = generateProductHashMap(products);
	}

	public static Map<Integer, ProductInfo> getProducts() {
		return mProducts;
	}

	public static Map<Integer, DepartmentData> getDepartments() {
		return mDepartments;
	}

	private void changeOrderState(OrderState state) {
		mTabbedPane.changeOrderState(state);
	}
	
	public Order createOrder() {
		return mTabbedPane.createOrder();
	}

	public void saved(SaveResponse status, boolean submitted) {
		mParent.setCursor(Cursor.getDefaultCursor());
		if (status != null && status.isSuccessfull()) {
			if (submitted) {
				changeOrderState(OrderState.Submitted);
				enableEdit(false);
			}
			mTabbedPane.saved(status.getOrderId());
			JOptionPane.showMessageDialog(this, "Zapisano.", "Stan zapisu", JOptionPane.INFORMATION_MESSAGE);
		} else
			JOptionPane.showMessageDialog(this, "Zapisywanie nie powiod\u0142o si\u0119!", "Stan zapisu",
					JOptionPane.ERROR_MESSAGE);
	}

	public void resetOrder() {
		mTabbedPane.resetOrder();
		enableEdit(true);
	}

	public void orderLoaded(OrderResponse response) {
		resetOrder();
		if (response.isSuccessfull()) {
			mTabbedPane.loadOrder(response.getOrder());
			
			mParent.setCursor(Cursor.getDefaultCursor());
			JOptionPane.showMessageDialog(this, "Zam\u00f3wienie wczytano.", "Stan \u0142adowania",
					JOptionPane.INFORMATION_MESSAGE);
		} else {
			mParent.setCursor(Cursor.getDefaultCursor());
			JOptionPane.showMessageDialog(this, "Nie mo\u017cna za\u0142adowa\u0107 zam\u00f3wienia.", "Stan \u0142adowania",
					JOptionPane.ERROR_MESSAGE);
		}
	}

	public void showOrderList(GetOrderListResponse orderList) {
		OrderListDialog dlg = new OrderListDialog(orderList, mDepartments);
		dlg.pack();
		dlg.setModal(true);
		dlg.setLocationRelativeTo(this);
		mParent.setCursor(Cursor.getDefaultCursor());
		dlg.setVisible(true);

		Order order = dlg.getDialogResponse();
		if (order != null) {
			mParent.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
			new GetOrderWorker(order.getDbId(), this).execute();
		}
	}
	
	private void enableEdit(boolean enable) {
		mTabbedPane.enableEdit(enable);
	}
}
